//
//  EPDateViewController.swift
//  EPHome
//
//  Created by liujianlong on 2022/9/5.
//

import UIKit

class EPDateViewController: EPAlertViewController {
    @IBOutlet var pickerview: UIPickerView!
    private var defaultDate:DateComponents?
    private var selectDate:DateComponents?
    var block:((_ stamp : Int, _ date:DateComponents)->Void)?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initUI()
    }
    
    override func initUI() {
        self.defaultDate = NSDate.dateOfStamp(0)
        self.selectDate = self.defaultDate
        self.pickerview.reloadAllComponents()
        self.pickerview.selectRow(self.defaultDate!.year!, inComponent: 0, animated: false)
        self.pickerview.selectRow(self.defaultDate!.month! - 1, inComponent: 1, animated: false)
        self.pickerview.selectRow(self.defaultDate!.day! - 1, inComponent: 2, animated: false)
    }
    
    @IBAction func actionForOK(_ sender: UIButton){
        self.block?(self.stamp(self.selectDate!.day!), self.selectDate!)
        self.dismiss(animated: false)
    }
    
    func stamp(_ day:Int)->Int{
        let str = String(format: "%d/%d/%d", self.selectDate!.year!, self.selectDate!.month!, day)
        return NSDate.tranToStamp(str, "yyyy/MM/dd").intValue()
    }
}

//MARK: - UIPickerViewDataSource
extension EPDateViewController:UIPickerViewDataSource{
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 3
    }
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if component == 0{
            return 100
        }else if component == 1{
            return 12
        }else{
            return NSDate.numOfMonth(self.stamp(1))
        }
    }
}
//MARK: - UIPickerViewDelegate
extension EPDateViewController:UIPickerViewDelegate{
    func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
        return 100
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if component == 0{
            self.selectDate?.year = self.defaultDate!.year! - row
        }else if component == 1{
            self.selectDate?.month = row + 1
        }else{
            self.selectDate?.day = row + 1
        }
        pickerview.reloadComponent(2)
    }
    
    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        let lbl = UILabel()
        lbl.textAlignment = .center
        lbl.textColor = HEX_BLUE
        lbl.font = FONT_TITLE
        if component == 0{
            lbl.text = String(format:LS("%d年"), self.defaultDate!.year! - row)
        }else if component == 1{
            lbl.text = LS(String(format:"%d月", row + 1))
        }else{
            lbl.text = String(format:LS("%d日"), row + 1)
        }
        return lbl
    }
}
